﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using DoublyUtils;
using System.Drawing;
using System.IO;
using System.Collections.Specialized;
using System.Drawing.Imaging;
using System.Runtime.Serialization.Formatters.Binary;
using static System.Windows.Forms.DataFormats;

namespace MyClipboardApplication
{
    public class ClipboardUtils
    {
        private LogUtils log = LogUtils.getInstance(typeof(ClipboardUtils));

        
        /// <summary>
        /// 存储剪贴板的文件内容
        /// </summary>
        /// <param name="append">是否以追加的方式存储</param>
        /// <returns>是否执行存储操作</returns>
        public Boolean saveFiles(String directoryPath)
        {
            try
            {
                //delete old files
                if (Directory.Exists(directoryPath))
                {
                    DirectoryUtils.deleteDirectory(directoryPath);
                }

                StringCollection files = Clipboard.GetFileDropList();
                //FileUtils.Write(this.extFilePath, Encoding.UTF8.GetBytes("FILES"), append);
                //Write(this.txtPath.Text + "//" + this.directoryName + "//" + this.extFileName, Encoding.UTF8.GetBytes("FILES"), append);
                for (int i = 0; i < files.Count; i++)
                {
                    String file = files[i];
                    String fileName = Path.GetFileName(file);
                    Directory.CreateDirectory(directoryPath);
                    try
                    {
                        if (File.Exists(file))
                            File.Copy(file, Path.Combine(directoryPath, fileName));
                        else if (Directory.Exists(file))
                        {
                            DirectoryUtils.copyDirectory(file, Path.Combine(directoryPath, fileName));
                        }
                    }
                    catch (Exception ex)
                    {
                        log.error(ex.Message);
                        log.error(ex.StackTrace);
                        return false;
                    }
                }

                log.info("copy files");
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                log.error(ex.StackTrace);
                return false;
            }
            return true;
        }

        /*
        /// <summary>
        /// 存储剪贴板的文字内容
        /// </summary>
        /// <param name="append">是否以追加的方式存储</param>
        /// <returns>是否进行存储操作</returns>
        public Boolean saveText(Boolean append)
        {
            try
            {
                //RTF
                if (Clipboard.ContainsData(DataFormats.Rtf))
                {
                    String rtf = (String)Clipboard.GetData(DataFormats.Rtf);
                    //String rtf = Clipboard.GetText(TextDataFormat.Rtf).ToString();

                    FileUtils.Write(this.extFilePath, Encoding.UTF8.GetBytes("RTF"), append);
                    FileUtils.Write(this.textFilePath, Encoding.UTF8.GetBytes(rtf));
                    log.info("copy rtf");
                }
                else
                {
                    //普通文本
                    //String str = (String)Clipboard.GetData(DataFormats.Text);
                    String str = Clipboard.GetText();
                    FileUtils.Write(this.extFilePath, Encoding.UTF8.GetBytes("TEXT"), append);
                    FileUtils.Write(this.textFilePath, Encoding.UTF8.GetBytes(str));

                    log.info("copy text:" + str);
                }
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                log.error(ex.StackTrace);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 存储剪贴板的图片内容
        /// </summary>
        /// <param name="append">是否以追加的方式存储</param>
        /// <returns>是否进行存储操作</returns>
        public Boolean saveImage(Boolean append)
        {
            try
            {
                Image img = Clipboard.GetImage();
                FileUtils.Write(this.extFilePath, Encoding.UTF8.GetBytes("IMAGE"), append);
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, ImageFormat.Bmp);
                    img.Dispose();
                    FileStream fs = new FileStream(this.imageFilePath, FileMode.Create);
                    fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);

                    fs.Close();
                    ms.Close();
                }
                log.info("copy image");
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                log.error(ex.StackTrace);
                return false;
            }
            return true;
        }*/

        /// <summary>
        /// 从共享路径中获取剪贴板的内容，并存储到剪贴中
        /// </summary>
        public void setClipboard(String filePath,String directoryPath)
        {
            FileStream fs = null;

            if (!File.Exists(filePath))
                return;
            log.info("剪贴板内容发生变更");
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter bf = new BinaryFormatter();
                var clipboardData = (Dictionary<String, Object>)bf.Deserialize(fs);
                if(clipboardData.Count == 0)
                {
                    log.info("变更无内容");
                    return;
                }
                if (clipboardData.ContainsKey(DataFormats.FileDrop))
                {
                    String[] files = Directory.GetFiles(directoryPath);
                    String[] directories = Directory.GetDirectories(directoryPath);
                    StringCollection sc = new StringCollection();
                    foreach(var file in files)
                    {
                        sc.Add(file);
                    }
                    foreach(var directory in directories)
                    {
                        sc.Add(directory);
                    }
                    Clipboard.SetFileDropList(sc);
                }
                else {
                    IDataObject data = new DataObject();
                    foreach (var entry in clipboardData)
                    {
                        String format = entry.Key;
                        Format formatObj = DataFormats.GetFormat(format);
                        log.info(formatObj.Id + " ===> " + formatObj.Name);
                        //data.SetData(entry.Key, entry.Value);
                        data.SetData(entry.Value);
                    }

                    var formats = data.GetFormats();

                    Clipboard.SetDataObject(data);

                    //Clipboard.SetDataObject(clipboardData);
                }
                log.info("剪贴板反序列化完成");
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                log.error(ex.StackTrace);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
        }

        /*
        /// <summary>
        /// 读取图片
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Image ReadAsImage(String path)
        {
            if (!File.Exists(path)) return null;
            return Image.FromFile(path);
        }
        */
    }
}
